//
//  HBViewController.m
//  HBBLeSDk
//
//  Created by LinRuiBin on 08/21/2020.
//  Copyright (c) 2020 LinRuiBin. All rights reserved.
//

#import "HBViewController.h"
#import "CurrentDeviceDetailViewController.h"
#import "HSDFUViewController.h"

@interface HBViewController ()<UITableViewDelegate,UITableViewDataSource,EGMBleHandlerDelagate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) NSArray *dataSource;
@property (nonatomic,strong) NSArray *deviceArr;
@property (nonatomic,strong) UILabel *statusLabel;
@end

@implementation HBViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"测试";
      [EGMBleHandler sharedBleHandler].delegate = self;
    [self addStatusLabel];
    [self addTestData];
    [self scannPeerDevice];
}

-(void)handleMsgBtPowerOn{
  _statusLabel.text = @"当前状态:蓝牙已打开";
}

-(void)handleMsgBtPowerOff{
    _statusLabel.text = @"当前状态:蓝牙已关闭";
}

-(void)handleMsgConnected{
    [self updateConnectStatus];
}

-(void)handleMsgDisconnected{
    
     _statusLabel.text = @"当前状态:断开连接";
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self updateConnectStatus];
}

-(void)updateConnectStatus{
    _statusLabel.text = @"当前状态:未连接";
       if ([EGMBleHandler sharedBleHandler].deviceIsConnected) {
           _statusLabel.text = [NSString stringWithFormat:@"当前状态:已连接\n当前连接设备:%@",[EGMBleHandler sharedBleHandler].bleManager.discoveredPeripheral.name];
       }
    
}

-(void)addStatusLabel{
    _statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 375, 120)];
    _statusLabel.numberOfLines = 0;
    _statusLabel.textColor = [UIColor redColor];
    _statusLabel.text = @"当前状态:未连接";
    _statusLabel.textAlignment = NSTextAlignmentCenter;
    self.tableView.tableFooterView  =_statusLabel;
}

-(void)appenTxetToStatusLabel:(NSString*)str{
    if (!str) return;
    _statusLabel.text =[NSString stringWithFormat:@"当前状态:%@",str];
    
}

-(void)addTestData{
    self.dataSource = @[@"扫描新设备",@"连接刚才的设备",@"前往设备协议测试页面",@"前往DFU 固件升级测试界面"];
    self.deviceArr = @[];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger section = indexPath.section;
    
    NSString *ideti = @"resueCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ideti];
           if (!cell) {
               cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ideti];
           }
    if (section == 0) {
        NSString *str = [self.dataSource objectAtIndex:indexPath.row];
        cell.textLabel.text = str;
    }else if (section == 1){
          CBPeripheral *per = [self.deviceArr objectAtIndex:indexPath.row];
        cell.textLabel.text = [NSString stringWithFormat:@"设备名字:%@,标识：%@",per.name,[per.identifier UUIDString]];
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return self.dataSource.count;
    }else if (section == 1){
        return self.deviceArr.count;
    }else{
        return 0;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSInteger row = indexPath.row;
    if (indexPath.section == 0) {
        if (row == 0) {
            [self scannNewDevice];
        }else if (row == 1){
            [self scannPeerDevice];
        }else if (row == 2){
            [self gototDeTAil];
        }else if (row==3){
            [self gotoDFU];
        }
    }else if (indexPath.section == 1) {
        CBPeripheral *per = [self.deviceArr objectAtIndex:indexPath.row];
         [self appenTxetToStatusLabel:@"正在连接"];
        [[EGMBleHandler sharedBleHandler] connectPeripheral:per conectBlok:^(BOOL isConnect) {
            NSLog(@"连接新设备%@",isConnect?@"成功":@"失败");
            [self updateConnectStatus];
            [[NSUserDefaults standardUserDefaults] setObject:[per.identifier UUIDString] forKey:@"cacheuuid"];
        }];
    }else{
        
    }
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section==1) {
        return @"扫描得到的新设备列表";
    }
    return @"";
}
#pragma mark - action

-(void)scannNewDevice{
    [self appenTxetToStatusLabel:@"正在扫描符合条环的所有设备，连接过的请先在手机蓝牙设置中忽略。"];
    [[EGMBleHandler sharedBleHandler] scanBLeDeviceWtihBlock:^(NSArray<CBPeripheral *> *peripherals) {
        [self appenTxetToStatusLabel:@"扫描设备完成,点击进行连接"];
        if (peripherals.count) {
            self.deviceArr = peripherals;
                 [self.tableView reloadData];
        }
     
    }];
}

-(void)scannPeerDevice{
    [self appenTxetToStatusLabel:@"尝试连接上一个缓存的设备"];
    NSString *cacheUUid =[[NSUserDefaults standardUserDefaults] objectForKey:@"cacheuuid"];
    if (cacheUUid) {
        [[EGMBleHandler sharedBleHandler] tryToScanAndConnectPeripheralWIthNSUUIDStr:cacheUUid conectBlok:^(BOOL isConnect) {
             NSLog(@"连接缓存设备%@",isConnect?@"成功":@"失败");
            [self updateConnectStatus];
            
        }];
    }else{
         [self appenTxetToStatusLabel:@"没有缓存的设备"];
    }
}

-(void)gototDeTAil{
    if (![EGMBleManager sharedBleManager].isBluetoothOn||![EGMBleHandler sharedBleHandler].deviceIsConnected) {
          [self appenTxetToStatusLabel:@"蓝牙未打开或设备未连接，不能跳转协议界面\n如果设备扫描不出来，请到手机蓝牙设置中忽略设备后重试"];
        return;
    }
    CurrentDeviceDetailViewController *detailVc = [[CurrentDeviceDetailViewController alloc] initWithNibName:NSStringFromClass([CurrentDeviceDetailViewController class]) bundle:nil];
    detailVc.modalPresentationStyle = 0;
    [self.navigationController pushViewController:detailVc animated:YES];
}

-(void)gotoDFU{
    if (![EGMBleManager sharedBleManager].isBluetoothOn||![EGMBleHandler sharedBleHandler].deviceIsConnected) {
             [self appenTxetToStatusLabel:@"蓝牙未打开或设备未连接，不能跳转升级界面\n如果设备扫描不出来，请到手机蓝牙设置中忽略设备后重试"];
           return;
       }
    HSDFUViewController *dfu = [[HSDFUViewController alloc] initWithNibName:NSStringFromClass([HSDFUViewController class]) bundle:nil];
      [self.navigationController pushViewController:dfu animated:YES];
    
}


@end
